package JavaServlet.TimeServlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Entity.PageBeanStudent;
import Entity.User;
import Service.IStudentService;
import Service_Impl.StudentServiceImpl;
import common.ServerResponse;
import net.sf.json.JSONArray;


@WebServlet("/student")
public class StudentServlets extends HttpServlet{

	private IStudentService studentService = new StudentServiceImpl();
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		 req.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");
		
		// 登录验证
//		HttpSession session = req.getSession();
//		User user = (User)session.getAttribute("user");
//		if(user == null) {
//			// 用户没有登录，重定向登录界面
//			resp.sendRedirect(req.getContextPath() + "/login.jsp");
//			return;
//		}
		if(method == null || "".equals(method)) {
			method = "pageList";
		}
		
		switch (method) {
		case "selectAll":
			selectAll(req,resp);
			break;
		case "insert":
			insert(req,resp);
			break;
		case "deleteById":
			deleteById(req,resp);
			break;
		case "searchName":
			searchName(req,resp);
			break;
		case "toUpdate":
			toUpdate(req,resp);
			break;
		case "update":
			update(req,resp);
			break;
		case "pageList":
			pageList(req,resp);
			break;
		case "checkName":
			checkName(req,resp);
			break;
		case "chooseBanji":
			chooseBanji(req,resp);
			break;
		default:
			System.out.println("default");
			break;
		}
	}

	private void chooseBanji(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		
		ArrayList<Banji> list = new ArrayList<Banji>();
		ResultSet resultSet = null;
		Connection connection = null;
		Statement statement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "select id, name from banji";
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				Banji banji = new Banji(id, name);
				list.add(banji);
			}
			for (Banji banji : list) {
				System.out.println(banji);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(connection, statement, resultSet);
		}
//		Banji banji1 = new Banji(1,"java1907");
//		Banji banji2 = new Banji(2,"java1912");
//		list.add(banji1);
//		list.add(banji2);
		
		req.setAttribute("list", list);
		req.getRequestDispatcher("/student_insert.jsp").forward(req, resp);
		
//		JSONArray jsonArray = JSONArray.fromObject(list);
//		resp.setContentType("text/css;charset=utf-8");
//		resp.getWriter().write(jsonArray.toString());
	}

	private void checkName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String checkName = req.getParameter("checkName");
		boolean isExist = studentService.checkName(checkName);
		
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().write("{\"isExist\":" + isExist + "}");
	}

	private void pageList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pageNo = req.getParameter("pageNo");
		String pageSize = req.getParameter("pageSize");
		
		if(pageNo == null || "".equals(pageNo)) {
			pageNo = "1";
		}
		if(pageSize == null || "".equals(pageSize)) {
			pageSize = "3";
		}
		
		PageBeanStudent pageBeanStudent = studentService.pageList(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
		System.out.println(pageBeanStudent);
		req.setAttribute("pageBeanStudent", pageBeanStudent);
		req.getRequestDispatcher("student_page_list.jsp").forward(req, resp);
	}

	private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("StudentServlets.update()");
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		//String banjiId = req .getParameter("banjiId");
		
		Student student = new Student(Integer.parseInt(id), name, Integer.parseInt(age), gender);
		boolean isSuccess = studentService.update(student);
		ServerResponse serverResponse = null;
		if(isSuccess) {
			serverResponse = ServerResponse.createSuccess("修改成功");
		}else {
			serverResponse = ServerResponse.createError("修改失败");
		}
		JSONUtil.obj2Json(resp, serverResponse);
		//resp.sendRedirect(req.getContextPath() + "/student");
	}

	private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("StudentServlets.toUpdate()");
		String updateId = req.getParameter("id");
		
		Student student = studentService.selectById(Integer.parseInt(updateId));
		System.out.println(student);
		//boolean isSuccess = studentService.update(student);
		req.setAttribute("student", student);
		req.getRequestDispatcher("/student_update.jsp").forward(req, resp);
	}

	private void searchName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("StudentServlets.searchName()");
		// 1、得到前端的数据
		String searchName = req.getParameter("searchName");
		// 2、调用Service层方法
		List<Student>list = studentService.searchName(searchName);
		// 3、进行页面的控制
		// 放到一块内存区域里面
		req.setAttribute("list", list);
		// 请求转发到student_list.jsp页面进行展示
		req.getRequestDispatcher("/student_list.jsp").forward(req, resp);
	}

	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");
		boolean isSuccess = studentService.deleteById(Integer.parseInt(id));
		// 删除完了之后重定向到列表界面再展示所有数据
		ServerResponse serverResponse = null;
		if(isSuccess) {
			serverResponse = ServerResponse.createSuccess("删除成功");
		}else {
			serverResponse = ServerResponse.createError("删除失败");
		}
		//resp.sendRedirect(req.getContextPath()+"/student?method=pageList");
		JSONUtil.obj2Json(resp, serverResponse);
	}

	private void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("StudentServlets.insert()");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		String banjiId = req .getParameter("banjiId");
		
		Student student = new Student(name, Integer.parseInt(age), gender, Integer.parseInt(banjiId));
		boolean isSuccess = studentService.insert(student);
		ServerResponse serverResponse = null;
		if(isSuccess) {
			serverResponse = ServerResponse.createSuccess("添加成功");
		}else {
			serverResponse = ServerResponse.createError("添加失败");
		}
		//resp.sendRedirect("/JavaWeb190703/student");
		JSONUtil.obj2Json(resp, serverResponse);
	}

	private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		List<Student>list = studentService.selectAll();
		
		// 放到一块内存区域里面
		req.setAttribute("list", list);
		// 请求转发到student_list.jsp页面进行展示
		req.getRequestDispatcher("/student_list.jsp").forward(req, resp);
	}
	
	//非递归阶乘
//	public static void main(String[] args) {
//		int result = factorial(5);
//		System.out.println(result);
//	}
//
//	private static int factorial(int n) {
//		int sum = 1;
//		for (int i = n; i >= 1; i--) {
//			sum *= i;
//		}
//		return sum;
//	}
	
	//递归阶乘
//	public static void main(String[] args) {
//		int result = factorial(10);
//		System.out.println(result);
//	}
//
//	private static int factorial(int i) {
//		if(i == 1) {
//			return 1;
//		}
//		return factorial(i - 1) * i;
//	}
}
